package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.Contract;
import com.neusoft.neuiotms.dcam.fixed.model.QContract;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedContractRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedContractRepositoryImpl extends AbstractRepository
        implements CustomizedContractRepository {

    @Override
    public Page<Contract> search(final Pageable pageable, final Searchable searchable) {
        final QContract qContract = QContract.contract;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Contract> query = this.query().selectFrom(qContract).orderBy(qContract.signingDate.desc());
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Contract.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QContract qContract = QContract.contract;

        where.and(super.containsStr(qContract.name, searchable, "name"));
        where.and(super.containsStr(qContract.code, searchable, "code"));
        // where.and(super.containsStr(qContract.manufacturer.name, searchable, "supplierName"));
        // where.and(super.containsStr(qContract.manufacturer.address, searchable, "supplierAddress"));
        // where.and(super.equalsBool(qContract.paymentStatus, searchable, "paymentStatus"));

        final String globalName = searchable.getStrValue("globalName");
        if (!StringUtils.isEmpty(globalName)) {
            where.or(super.containsStr(qContract.name, searchable, "globalName"));
            where.or(super.containsStr(qContract.code, searchable, "globalName"));
            where.or(super.containsStr(qContract.manufacturer, searchable, "globalName"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("signingDateStart"))) {
            where.and(
                    super.afterOrEqualsDate(qContract.signingDate, searchable, "signingDateStart"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("signingDateEnd"))) {
            where.and(super.beforeOrEqualsDate(qContract.signingDate, searchable, "signingDateEnd"));
        }
        return where;
    }

}
